package com.cheer.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import com.cheer.common.Page;
import com.cheer.common.Result;
import com.cheer.dto.LecTeacherAddDTO;
import com.cheer.entity.OaAdminEntity;
import com.cheer.enums.AdminRoleEnum;
import com.cheer.enums.LectureTypeEnum;
import com.cheer.exception.ServiceException;
import com.cheer.param.LecTeacherListParam;
import com.cheer.security.UserInfoHolder;
import com.cheer.service.LecTeacherService;
import com.cheer.vo.*;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.One;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author cheer
 */
@RestController
@RequestMapping("/teacher")
@Api(tags="讲师")
public class LecTeacherController {

    @Autowired
    private LecTeacherService lecTeacherService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @PostMapping("/list")
    public Result<Page<LecTeacherVO>> list( @RequestBody LecTeacherListParam lecTeacherListParam ) {
        if (lecTeacherListParam.getOrg() == null) {
            lecTeacherListParam.setOrg(userInfoHolder.getAdmin().getPid());
        }
        return Result.success(lecTeacherService.listByPage(lecTeacherListParam));
    }

    /**
     * 讲师宣讲次数统计功能-柱状图
     * @return
     */
    @ApiOperation("讲师宣讲次数统计功能-柱状图")
    @PostMapping("/teacherLectureCount")
    public Result countLecture(@RequestBody LecTeacherListParam lecTeacherListParam) {
        List<TeacherLectureCountVo> teacherLectureCount =
                lecTeacherService.queryTeacherLectureCount(lecTeacherListParam.getStartTime(),
                                                            lecTeacherListParam.getEndTime(),
                                                            lecTeacherListParam.getType());
        List<String> xData = Lists.newArrayList();
        List<Integer> yData = Lists.newArrayList();
        List<Integer> scoreAllData = Lists.newArrayList();
        for (TeacherLectureCountVo teacherLectureCountVo : teacherLectureCount) {
            xData.add(teacherLectureCountVo.getName());
            yData.add(teacherLectureCountVo.getNum().intValue());
            scoreAllData.add(teacherLectureCountVo.getScore().intValue());
        }
        //将teacherLectureCount列表转换成柱状图的格式，按照次数排序，姓名为x轴，次数为y轴
        List<Integer> OneData = Lists.newArrayList();  //省级示范 分值
        List<Integer> TwoData = Lists.newArrayList(); //团中央示范 分值
        List<Integer> ThreeData = Lists.newArrayList(); //日常示范 分值
//        teacherLectureCount.forEach(teacher -> {
//            Long teacherId = teacher.getTeacherId();
//            List<LecTeacherCourseDetailVo> courseDetails = lecTeacherService.queryCourseTypeSeries(lecTeacherListParam.getStartTime(),
//                    lecTeacherListParam.getEndTime(),
//                    teacherId, lecTeacherListParam.getType());
//            //如果courseDetails长度为1，说明只有一种课程类型，自动将其他两种类型的分值置为0
//            if (courseDetails.size() == 1) {
//                if (courseDetails.get(0).getCourseType() == 1) {
//                    OneData.add(5*courseDetails.get(0).getNum());
//                    TwoData.add(0);
//                    ThreeData.add(0);
//                } else if (courseDetails.get(0).getCourseType() == 2) {
//                    OneData.add(0);
//                    TwoData.add(3*courseDetails.get(0).getNum());
//                    ThreeData.add(0);
//                } else if(courseDetails.get(0).getCourseType() == 3){
//                    OneData.add(0);
//                    TwoData.add(0);
//                    ThreeData.add(1*courseDetails.get(0).getNum());
//                }else {
//                    OneData.add(0);
//                    TwoData.add(0);
//                    ThreeData.add(0);
//                }
//            } else if(courseDetails.size() == 2){
//                //如果courseDetails长度为2，说明有两种课程类型，自动将另一种类型的分值置为0
//                if(courseDetails.get(0).getCourseType() == 1 && courseDetails.get(0).getCourseType() == 2){
//                    OneData.add(5*courseDetails.get(0).getNum());
//                    TwoData.add(3*courseDetails.get(1).getNum());
//                    ThreeData.add(0);
//                }else if(courseDetails.get(0).getCourseType() == 1 && courseDetails.get(1).getCourseType() == 3){
//                    OneData.add(5*courseDetails.get(0).getNum());
//                    TwoData.add(0);
//                    ThreeData.add(1*courseDetails.get(1).getNum());
//                }else if(courseDetails.get(0).getCourseType() == 2 && courseDetails.get(1).getCourseType() == 3){
//                    OneData.add(0);
//                    TwoData.add(3*courseDetails.get(0).getNum());
//                    ThreeData.add(1*courseDetails.get(1).getNum());
//                }
//
//            }else if(courseDetails.size() == 3){
//                //如果courseDetails长度为3，说明有三种课程类型
//                OneData.add(5*courseDetails.get(0).getNum());
//                TwoData.add(3*courseDetails.get(1).getNum());
//                ThreeData.add(1*courseDetails.get(2).getNum());
//            }
//            xData.add(teacher.getName());
//            yData.add(teacher.getNum().intValue());
//            scoreAllData.add(teacher.getNum().intValue());
//        });
        return Result.success(new TeacherLectureCountChartVo(xData, yData, OneData, TwoData, ThreeData, scoreAllData));
    }

    private static class TeacherLectureCountChartVo {
        private List<String> xData;
        private List<Integer> yData;

        private List<Integer> OneData;
        private List<Integer> TwoData;
        private List<Integer> ThreeData;
        private List<Integer> scoreAllData;

        public TeacherLectureCountChartVo(List<String> xData,
                                          List<Integer> yData,
                                          List<Integer> OneData,
                                          List<Integer> TwoData,
                                          List<Integer> ThreeData,
                                          List<Integer> scoreAllData) {
            this.OneData = OneData;
            this.TwoData = TwoData;
            this.ThreeData = ThreeData;
            this.scoreAllData = scoreAllData;
            this.xData = xData;
            this.yData = yData;
        }

        public List<String> getxData() {
            return xData;
        }

        public void setxData(List<String> xData) {
            this.xData = xData;
        }

        public List<Integer> getyData() {
            return yData;
        }

        public void setyData(List<Integer> yData) {
            this.yData = yData;
        }

        public List<Integer> getOneData() {
            return OneData;
        }

        public void setOneData(List<Integer> oneData) {
            OneData = oneData;
        }

        public List<Integer> getTwoData() {
            return TwoData;
        }

        public void setTwoData(List<Integer> twoData) {
            TwoData = twoData;
        }

        public List<Integer> getThreeData() {
            return ThreeData;
        }

        public void setThreeData(List<Integer> threeData) {
            ThreeData = threeData;
        }

        public List<Integer> getScoreAllData() {
            return scoreAllData;
        }

        public void setScoreAllData(List<Integer> scoreAllData) {
            this.scoreAllData = scoreAllData;
        }
    }

    // 教师注册
    public  Result register(HttpServletRequest request, String codeInRequest){
        lecTeacherService.register(request, codeInRequest);
        return Result.success();
    }

    @ApiOperation("批量下载接口")
    @GetMapping("/templateDownload")
    public void templateDownload() {
        try {
            lecTeacherService.templateDownload();
        } catch (IOException e) {
            throw new ServiceException("下载模板异常");
        }
    }

    @ApiOperation("批量导入接口")
    @PostMapping("/batchImport")
    public Result<List<String>> batchImport(MultipartFile file) {

        List<String> list = lecTeacherService.batchImport(file);
        if(CollectionUtil.isEmpty(list)){
            return Result.success();
        }
        String exceptionRecord = list.stream().collect(Collectors.joining("<br/>"));
        Console.log(exceptionRecord);
        return Result.error(500, exceptionRecord);
    }

    @GetMapping("/types")
    public Result<List<SelectOptVO>> types() {

        List<SelectOptVO> lectureTypeSelect = LectureTypeEnum.getLectureTypeSelect();
        return Result.success(lectureTypeSelect);
    }

    /**
     *
     * @return
     */
    @GetMapping("/getUserLinkedTeaInfo")
    public Result<LecCurrentTeaVO> getUserLinkedTeaInfo(){

        LecCurrentTeaVO vo = lecTeacherService.getUserLinkedTeaInfo();

        return Result.success(vo);
    }

    @PostMapping("/download")
    public void download(@RequestBody LecTeacherListParam lecTeacherListParam) {

        if (lecTeacherListParam.getOrg() == null) {
            lecTeacherListParam.setOrg(userInfoHolder.getAdmin().getPid());
        }
        lecTeacherService.download(lecTeacherListParam);
    }

    @PostMapping("/add")
    @ApiOperation(value = "讲师添加", notes = "讲师添加", httpMethod = "POST")
    public Result add(@RequestBody @Valid LecTeacherAddDTO addDTO) {
        lecTeacherService.add(addDTO);
        return Result.success();
    }

    @GetMapping("/info")
    public Result<LecTeacherInfoVO> info(@RequestParam Integer id) {

        String  adminMark = "0";
        OaAdminEntity admin = userInfoHolder.getAdmin();
        LecTeacherInfoVO info = lecTeacherService.info(id);
        // teachers are only allowed to check their own information
        if(admin.getRoleId().equals(AdminRoleEnum.TEACHER.getCode())){
            if(info.getAccount().equals(admin.getAdTel())){
                return Result.success(info);
            }
        }
        // whether other role can match the current user
        String teacherPath = info.getPath().stream().map(String::valueOf).collect(Collectors.joining(new String(",")));
        if(teacherPath.contains( String.valueOf(admin.getPid()) ) || adminMark.equals(String.valueOf(admin.getPid())) ){
            for (int i = 0; i < info.getPath().size(); i++) {
                if (Objects.equals(info.getPath().get(i), userInfoHolder.getAdmin().getPid())) {
                    info.setPath(info.getPath().subList(i, info.getPath().size()));
                    break;
                }
            }
            return Result.success(info);
        }else{
            throw new ServiceException("当前用户没有权限查询此用户信息！");
        }
    }

    @PostMapping("/update")
    public Result update(@RequestBody @Valid LecTeacherAddDTO addDTO) {
        lecTeacherService.update(addDTO);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody @Valid List<Integer> ids) {
        lecTeacherService.delete(ids);
        return Result.success();
    }

    @PostMapping("/reset")
    public Result reset(@RequestParam Integer id) {
        lecTeacherService.reset(id);
        return Result.success();
    }

}
